//
//  LLAlbumsViewController.m
//  LLCoreUserInterface
//
//  Created by my_liu on 2016/11/16.
//  Copyright © 2016年 my_liu. All rights reserved.
//

#import "LLAlbumsViewController.h"
#import "LLPhotosViewController.h"
#import "LLAlbums.h"
#import "LLAssetsPickerAlbumsCell.h"
#import "LLAssetsPickerConstans.h"
#import "LLUitils.h"
#import "LLAssetsPickerStyleManager.h"

#define kLLPhotoViewControllerCustomKey      @"kLLPhotoViewControllerCustomKey"
#define kLLAlbumsViewControllerCellCustomKey @"kLLAlbumsViewControllerCellCustomKey"
#define kLLAlbumsViewControllerCellCustomHeightKey @"kLLAlbumsViewControllerCellCustomHeightKey"

@interface LLAlbumsViewController ()<UITableViewDataSource,UITableViewDelegate,LLPhotosViewControllerDelegate>
{
    __weak LLPhotosViewController *_photosVC;
}

@property (nonatomic,strong)ALAssetsLibrary *assetsLibrary;
@property (nonatomic,strong)UITableView *groupTable;
@property (nonatomic,strong)NSMutableArray *assetsGroupArray;
@property (nonatomic,strong)NSMutableDictionary *customClassDict;

@end

@implementation LLAlbumsViewController

- (id)init
{
    if (self = [super init]) {
        self.photoControllerColums = 4;//默认4行
        self.mutilSelectLimitCount = 0;//默认不限制选中数量
        self.customClassDict = [[NSMutableDictionary alloc]init];
        [self setupAlumbs];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.photoControllerColums = 4;//默认4行
        self.mutilSelectLimitCount = 0;//默认不限制选中数量
        self.customClassDict = [[NSMutableDictionary alloc]init];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    self.groupTable = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.groupTable.backgroundColor = [UIColor clearColor];
    [self.groupTable setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    self.groupTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.groupTable.delegate = self;
    self.groupTable.dataSource = self;
    if ([LLAssetsPickerConstans isIOS7]) {
        
        if ([self.groupTable respondsToSelector:@selector(setSeparatorInset:)]) {
            [self.groupTable setSeparatorInset:UIEdgeInsetsZero];
        }
        
        /* 适配iOS7 */
        CGRect groupTableFrame = self.groupTable.frame;
        groupTableFrame.size.height = self.view.frame.size.height - 64;
        self.groupTable.frame = groupTableFrame;
        
    }else{
        
        /* 适配iOS7以下 */
        CGRect groupTableFrame = self.groupTable.frame;
        groupTableFrame.size.height = self.view.frame.size.height - 44;
        self.groupTable.frame = groupTableFrame;
        
    }
    
    [self.view addSubview:self.groupTable];
    
    
    [self setupStyle];
    
    
}

- (void)setupAlumbs
{
    self.assetsGroupArray = [[NSMutableArray alloc]init];
    
    /* 使用全局的library ,否则造成 ALAsset 对象 离开Library对象之后就失效了 */
    self.assetsLibrary = [LLAssetsPickerConstans shareAssetsLibrary];
    
    
    void (^GetAlumbsGroupSuccessBlock) (ALAssetsGroup *,BOOL *) = ^(ALAssetsGroup *group,BOOL *stop){
        
        if (group == nil) {
            return ;
        }
        
        NSString *sGroupPropertyName = (NSString *)[group valueForProperty:ALAssetsGroupPropertyName];
        NSUInteger nType = [[group valueForProperty:ALAssetsGroupPropertyType] intValue];
        
        LLAlbums *albums = [[LLAlbums alloc]initWithAssetsGroup:group];
        albums.filter = self.assetsFilter;
        
        if (([[sGroupPropertyName lowercaseString] isEqualToString:@"camera roll"] || [[sGroupPropertyName lowercaseString] isEqualToString:@"相机胶卷"]) && nType == ALAssetsGroupSavedPhotos) {
            
            [self.assetsGroupArray insertObject:albums atIndex:0];
        }
        else {
            [self.assetsGroupArray addObject:albums];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.groupTable reloadData];
        });
        
        if (_photosVC) {
            if (self.assetsGroupArray.count >0) {
                _photosVC.albums = [self.assetsGroupArray objectAtIndex:0];
            }
        }
        
    };
    
    void (^GetAlumbsGroupFaildBlock) (NSError *) = ^(NSError *error){
        
        NSError *accessError = [NSError errorWithDomain:kLLAssetsPickerErrorDomain code:LLAssetsPickerErrorTypePhotoLibarayNotAuthorize userInfo:@{@"errorType":@(LLAssetsPickerErrorTypePhotoLibarayNotAuthorize)}];
        
        [LLAssetsPickerConstans postNoti:kLLAssetsPickerComeAcrossAnErrorNoti withObject:accessError];
        
    };
    
    [self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:GetAlumbsGroupSuccessBlock failureBlock:GetAlumbsGroupFaildBlock];
}
//设置
- (void)setupStyle
{
    LLAssetsPickerStyle *defaultStyle = [[LLAssetsPickerStyleManager share] style];
    
    //图片选择列表没一行的照片数量
    self.photoControllerColums = defaultStyle.numberOfColums;
    
    //navigationBar 背景
    if (defaultStyle.sysAlbumsNavigationBarDes.backgroundColor) {
        UIImage *colorImage = [LLAssetsPickerConstans imageForColor:defaultStyle.sysPhotoNavigationBarDes.backgroundColor withSize:CGSizeMake(self.view.frame.size.width,64)];
        [self.navigationController.navigationBar setBackgroundImage:colorImage forBarMetrics:UIBarMetricsDefault];
    }
    if (defaultStyle.sysPhotoNavigationBarDes.backgroundImage) {
        [self.navigationController.navigationBar setBackgroundImage:defaultStyle.sysPhotoNavigationBarDes.backgroundImage forBarMetrics:UIBarMetricsDefault];
    }
    
    //标题
    UILabel *titleLabel = [[UILabel alloc]init];
    [titleLabel setCommonStyleDescription:defaultStyle.sysAlbumsNavigationBarDes];
    self.title = defaultStyle.sysAlbumsNavigationBarDes.title;
    self.navigationItem.titleView = titleLabel;
    titleLabel = nil;
    
    //取消返回
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setCommonStyleDescription:defaultStyle.sysCancelBtnDes];
    //响应事件
    [cancelBtn addTarget:self action:@selector(dismissPickerViewController) forControlEvents:UIControlEventTouchUpInside];
    
    //设置Item
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc]initWithCustomView:cancelBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    rightBarItem = nil;
}

- (void)dismissPickerViewController
{
    [LLAssetsPickerConstans postNoti:kLLAssetsPickerNeedCancelNoti];
}

- (void)photoViewController:(LLPhotosViewController *)photoViewController didFinishEnumrateAssets:(NSArray *)assets forAlbums:(LLAlbums *)destAlbums
{
    for (int i= 0; i<self.assetsGroupArray.count; i++) {
        
        LLAlbums *albums = [self.assetsGroupArray objectAtIndex:i];
        
        if ([albums isEqual:destAlbums]) {
            
            [albums.assetsArray addObjectsFromArray:assets];
            
            [self.assetsGroupArray replaceObjectAtIndex:i withObject:albums];
            
            break;
        }
        
    }
}

#pragma mark - tableView delegate and dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.assetsGroupArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //自定义相册Cell
    NSDictionary *customCellDict = self.customClassDict[kLLAlbumsViewControllerCellCustomKey];
    NSString *customAlbumsCellClassName = [customCellDict objectForKey:kLLAlbumsViewControllerCellCustomKey];
    Class customAlbumsCellClass = NSClassFromString(customAlbumsCellClassName);
    
    if (customAlbumsCellClass && [customAlbumsCellClass isSubclassOfClass:[LLAssetsPickerAlbumsCell class]]) {
        
        static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
        LLAssetsPickerAlbumsCell *customCell = (LLAssetsPickerAlbumsCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
        if (!customCell) {
            customCell = [[customAlbumsCellClass alloc]init];
        }
        [customCell setAlbums:[self.assetsGroupArray objectAtIndex:indexPath.row]];
        [customCell setIsLast:([self.assetsGroupArray count] == indexPath.row + 1)];
        return customCell;
        
    }
    
    //使用系统的效果
    static NSString *CellIdentifier = @"CellIdentifier";
    LLAssetsPickerAlbumsCell *cell = (LLAssetsPickerAlbumsCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        cell = [[LLAssetsPickerAlbumsCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    [cell setAlbums:[self.assetsGroupArray objectAtIndex:indexPath.row]];
    [cell setIsLast:([self.assetsGroupArray count] == indexPath.row + 1)];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //自定义相册Cell
    NSDictionary *customCellDict = self.customClassDict[kLLAlbumsViewControllerCellCustomKey];
    if (customCellDict) {
        return [[customCellDict objectForKey:kLLAlbumsViewControllerCellCustomHeightKey] floatValue];
    }else{
        return 65.f;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //如果有自定义的选择照片的页面
    NSString *customPhotoControllerName = self.customClassDict[kLLPhotoViewControllerCustomKey];
    Class customPhotoControllerClass = NSClassFromString(customPhotoControllerName);
    
    if (customPhotoControllerName && [customPhotoControllerClass isSubclassOfClass:[LLPhotosViewController class]]) {
        
        LLPhotosViewController *customPhotoController = [[customPhotoControllerClass alloc]init];
        customPhotoController.colums = self.photoControllerColums;
        customPhotoController.albums = [self.assetsGroupArray objectAtIndex:indexPath.row];
        customPhotoController.mutilSelectLimitCount = self.mutilSelectLimitCount;
        customPhotoController.shouldInitSelectedStateAssetArray = self.shouldInitSelectedStateAssetArray;
        customPhotoController.delegate = self;
        customPhotoController.title = [(LLAlbums*)[self.assetsGroupArray objectAtIndex:indexPath.row] name];
        [self.navigationController pushViewController:customPhotoController animated:YES];
        
        return;
    }
    
    //使用系统效果
    LLPhotosViewController *photosViewController = [[LLPhotosViewController alloc]init];
    photosViewController.colums = self.photoControllerColums;
    photosViewController.delegate = self;
    photosViewController.albums = [self.assetsGroupArray objectAtIndex:indexPath.row];
    photosViewController.mutilSelectLimitCount = self.mutilSelectLimitCount;
    photosViewController.shouldInitSelectedStateAssetArray = self.shouldInitSelectedStateAssetArray;
    photosViewController.title = [(LLAlbums*)[self.assetsGroupArray objectAtIndex:indexPath.row] name];
    [self.navigationController pushViewController:photosViewController animated:YES];
    
}

#pragma mark - 对外接口

- (void)pushDefaultAlbums
{
    LLPhotosViewController *vc = [[LLPhotosViewController alloc]init];
    _photosVC = vc;
    _photosVC.colums = self.photoControllerColums;
    //    _photosVC.albums = [self.assetsGroupArray objectAtIndex:0];
    _photosVC.mutilSelectLimitCount = self.mutilSelectLimitCount;
    _photosVC.shouldInitSelectedStateAssetArray = self.shouldInitSelectedStateAssetArray;
    //    _photosVC.title = [(LLAlbums*)[self.assetsGroupArray objectAtIndex:0] name];
    [self.navigationController pushViewController:_photosVC animated:NO];
}

- (void)registPhotoViewControllerClass:(Class)aPhotoViewControllerClass
{
    if (!aPhotoViewControllerClass) {
        return;
    }
    [self.customClassDict setObject:NSStringFromClass(aPhotoViewControllerClass) forKey:kLLPhotoViewControllerCustomKey];
}

- (void)registAlbumsCustomCellClass:(Class)aAlbumsCustomCellClass
{
    if (!aAlbumsCustomCellClass) {
        return;
    }
    [self registAlbumsCustomCellClass:aAlbumsCustomCellClass withCellHeight:44.f];
}

- (void)registAlbumsCustomCellClass:(Class)aAlbumsCustomCellClass withCellHeight:(CGFloat)cellHeight
{
    if (!aAlbumsCustomCellClass) {
        return;
    }
    NSDictionary *customCellDict = @{kLLAlbumsViewControllerCellCustomKey:NSStringFromClass(aAlbumsCustomCellClass),kLLAlbumsViewControllerCellCustomHeightKey:@(cellHeight)};
    [self.customClassDict setObject:customCellDict forKey:kLLAlbumsViewControllerCellCustomKey];
}
@end
